﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace Tequila.Phone.Interactivity
{
    /// <summary>
    /// Should be used when associated object derived from <see cref="TextBox">TextBox</see> is wrapped by <see cref="ScrollViewer">ScrollViewer</see>.
    /// When Enter key is pressed, scroll automatically will be moved to new carriage position.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class AutoScrollTextBoxBehavior<T> : Behavior<T> where T : TextBox
    {

    }

    /// <summary>
    /// Should be used when <see cref="TextBox">TextBox</see> is wrapped by <see cref="ScrollViewer">ScrollViewer</see>.
    /// When Enter key is pressed, scroll automatically will be moved to new carriage position.
    /// </summary>
    public class AutoScrollTextBoxBehavior : AutoScrollTextBoxBehavior<TextBox>
    {
        private ScrollViewer _externalScrollViewer;

        /// <summary>
        /// Called after the behavior is attached to an AssociatedObject.
        /// </summary>
        /// <remarks>
        /// Override this to hook up functionality to the AssociatedObject.
        /// </remarks>
        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.SizeChanged += TextBoxSizeChanged;
        }

        /// <summary>
        /// Called when the behavior is being detached from its AssociatedObject, but before it has actually occurred.
        /// </summary>
        /// <remarks>
        /// Override this to unhook functionality from the AssociatedObject.
        /// </remarks>
        protected override void OnDetaching()
        {
            base.OnDetaching();
            AssociatedObject.SizeChanged -= TextBoxSizeChanged;
        }

        private void TextBoxSizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (_externalScrollViewer == null)
            {
                _externalScrollViewer = AssociatedObject.FindVisualParent<ScrollViewer>();
            }

            if (_externalScrollViewer != null && e.NewSize.Height > _externalScrollViewer.VerticalOffset)
            {
                _externalScrollViewer.ScrollToVerticalOffset(e.NewSize.Height);
            }
        }

    }
}
